package com.zhenyi.etcr.index.admin;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

import com.cjw.model.DBMap;
import com.jfinal.aop.Before;
import com.jfinal.kit.Kv;
import com.jfinal.kit.LogKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.DbPro;
import com.jfinal.plugin.activerecord.SqlPara;
import com.jfinal.plugin.ehcache.CacheInterceptor;
import com.jfinal.plugin.ehcache.CacheName;
import com.yitaicms.common.model.CmsArticle;
import com.zhenyi.api.FenciUtils;
import com.zhenyi.core.ZIndexController;
import com.zhenyi.search.SearchResult;
import com.zhenyi.search.SearchUtils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.text.StrFormatter;
import cn.hutool.http.HttpUtil;

public class SeoController extends ZIndexController {

	protected DbPro db = Db.use("yitaicms");

	@Override
	public void info() {
		Long id = getParaToLong("id");
		if (id == null) {
			// renderFailure(500, "id is null");
			redirect("/");
			return;
		}
		CmsArticle article = CmsArticle.dao.findById(id);
		// CmsCategory category =
		// CmsCategory.dao.findById(article.getCategoryId());
		// String title = category.getTitle();
		setInfoItem(article);
		setData("data", article);
		setAttr("nextArticle", getNArticle(id));
		// setAttr("previousArticle", getNArticle(id));
		setAttr("previousArticle", getPArticle(id));
		setAttr("words", FenciUtils.instance().run(article.getTitle()));
		// renderResult(article, title, 200);

		render("/yitai/info.html");
	}

	private CmsArticle getNArticle(Long id) {
		Kv kv = Kv.by("appId", 1);
		kv.set("id", id);
		SqlPara sqlPara = db.getSqlPara("YTFindNextArticle", kv);
		CmsArticle article = CmsArticle.dao.findFirst(sqlPara);
		return article;
	}

	private CmsArticle getPArticle(Long id) {
		Kv kv = Kv.by("appId", 1);
		kv.set("id", id);
		SqlPara sqlPara = db.getSqlPara("YTFindPreviousArticle", kv);
		CmsArticle article = CmsArticle.dao.findFirst(sqlPara);
		return article;
	}

	public void data() {
		Long id = getParaToLong("id");
		if (id == null) {
			renderFailure(500, "id is null");
			return;
		}
		CmsArticle article = CmsArticle.dao.findById(id);
		if (article == null) {
			renderFailure(500, "article is null");
			return;
		}
		renderSuccess(article);
	}

	@Override
	public void list() {
		try {
			String text = getPara("wd", "ETCR");
			SearchUtils searchUtils = new SearchUtils();
			int pageIndex = getPage();
			int pageSize = 10;
			String[] fields = new String[] { "title", "content", "description", "attach", "subtitle", "date" };
			HashMap<String, Object> result = searchUtils.search(text, fields, pageIndex, pageSize);
			@SuppressWarnings("unchecked")
			ArrayList<SearchResult> list = (ArrayList<SearchResult>) result.get("results");
			setItems(list);
			int totalPage = (int) result.get("totalPage");
			setAttr("page", pageIndex);
			setAttr("totalPage", totalPage);
			render("/yitai/list.html");
		} catch (Exception e) {
			renderFailure();
		}
	}

	@Override
	public void submit() {
		Long id = getParaToLong("id");
		CmsArticle article = CmsArticle.dao.findById(id);
		if (article == null) {
			renderFailure(404, "article not found");
			return;
		}
		String seoTitle = getPara("seoTitle");
		String seoDescription = getPara("seoDescription");
		String seoKeywords = getPara("seoKeywords");
		String description = getPara("description");
		if (StrKit.notBlank(seoDescription)) {
			article.setSeoDescription(seoDescription);
		}
		if (StrKit.notBlank(seoTitle)) {
			article.setSeoTitle(seoTitle);
		}
		if (StrKit.notBlank(seoKeywords)) {
			article.setSeoKeywords(seoKeywords);
		}
		if (StrKit.notBlank(description)) {
			article.setDescription(description);
		}
		article.setUpdateTime(DateUtil.now());
		article.update();
		Long categoryId = article.getCategoryId();
		String url = "http://www.etcr.com.cn";
		if (categoryId.equals(3L)) {
			LogKit.info("33");
			url = "http://www.etcr.com.cn/news/info?id=" + id;
		} else {
			url = "http://www.etcr.com.cn/product/info?id=" + id;
		}
		postUrl(url);
		renderSuccess(url);
	}

	private void postUrl(String url) {
		String requestUrl = "http://data.zz.baidu.com/urls?site=www.etcr.com.cn&token=8FndMN9DyB0kmwzL";
		String response = HttpUtil.post(requestUrl, url);
		System.out.println(response);
	}

	@Before(CacheInterceptor.class)
	@CacheName("30min")
	public void search() {
		// String word = "接地电阻在线检测仪";
		String text = getPara("text", "");
		if (StrKit.isBlank(text)) {
			renderFailure();
			return;
		}
		String url = "https://www.baidu.com/s?wd={}&pn={}&oq={}";
		for (int page = 0; page < 10; page++) {
			String requestUrl = StrFormatter.format(url, text, page * 10, text);
			String response = HttpUtil.get(requestUrl);
			// System.out.println(response);
			boolean flag = response.contains("www.etcr.com");
			if (flag) {
				// System.out.println("page " + page);
				// System.out.println(requestUrl);
				DBMap map = new DBMap();
				map.put("page", page + 1);
				map.put("url", requestUrl);
				map.put("word", text);
				renderSuccess(map);
				return;
			} else {
				// System.out.println("page " + page + " no found");
			}
		}
		// renderFailure();
		DBMap map = new DBMap();
		map.put("page", "10+");
		map.put("url", "");
		map.put("word", text);
		renderSuccess(map);
	}

}
